HJS

React Testing Library 완전 정리

1️⃣ React Testing Library란?

**React Testing Library(RTL)**는 React 컴포넌트를 사용자 관점에서 테스트하기 위해 만들어진 라이브러리입니다.


2️⃣ 설치

npm install --save-dev @testing-library/react @testing-library/jest-dom

3️⃣ 기본 사용법

🔹 컴포넌트 렌더링

// Counter.js
import { useState } from "react";

export default function Counter() {
  const [count, setCount] = useState(0);
  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={() => setCount(count + 1)}>증가</button>
    </div>
  );
}
// Counter.test.js
import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import Counter from "./Counter";

test("버튼 클릭 시 카운트가 증가한다", async () => {
  render(<Counter />);

  const button = screen.getByRole("button", { name: "증가" });
  await userEvent.click(button);

  expect(screen.getByText("Count: 1")).toBeInTheDocument();
});

4️⃣ 쿼리(Query) 메서드

RTL은 요소를 찾을 때 접근성(Accessibility) 기준을 권장합니다.

screen.getByRole("button", { name: "로그인" });
screen.getByLabelText("아이디");
screen.getByPlaceholderText("비밀번호 입력");
screen.getByText("회원가입");
메서드요소 없을 때사용 시점
getBy*에러 발생반드시 존재해야 할 때
queryBy*null 반환없을 수도 있을 때
findBy*Promise 반환비동기 요소 탐색 시

5️⃣ 사용자 이벤트 (user-event)

const input = screen.getByRole("textbox");
await userEvent.type(input, "Hello");

expect(input).toHaveValue("Hello");

6️⃣ Jest-DOM Matchers

@testing-library/jest-dom을 설치하면 DOM 전용 Matcher를 활용할 수 있습니다.

expect(screen.getByText("로그인")).toBeInTheDocument();
expect(screen.getByRole("textbox")).toHaveValue("Hello");

7️⃣ RTL의 핵심 철학